﻿using HslCommunication.Profinet.Omron;
using PLCDataCollector.Core.Entities;
using PLCDataCollector.Core.Interfaces;
using PLCDataCollector.Services.PLC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCDataCollector.Services
{
    public class PLCServiceFactory
    {
        // 使用字典映射协议类型到对应的创建函数
        private static readonly Dictionary<string, Func<string, int, IPLCService>> _protocolMappings =
            new Dictionary<string, Func<string, int, IPLCService>>(StringComparer.OrdinalIgnoreCase)
        {
                { "MelsecMcNet", (ip, port) => new MelsecMcNetService(ip, port) },
                { "MelsecA1EAsciiNet", (ip, port) => new MelsecA1EAsciiNetService(ip, port) },
                { "MelsecMcAsciiNet", (ip, port) => new MelsecMcAsciiNetService(ip, port) },
                { "MelsecA1ENet", (ip, port) => new MelsecA1ENetService(ip, port) },
                { "OmronFinsNet", (ip, port) => new OmronFinsNetService(ip, port) },
                
                // 可以继续添加其他协议映射
        };

        // 注册新的协议类型
        public static void RegisterProtocol(string protocolType, Func<string, int, IPLCService> creator)
        {
            if (_protocolMappings.ContainsKey(protocolType))
            {
                _protocolMappings[protocolType] = creator;
            }
            else
            {
                _protocolMappings.Add(protocolType, creator);
            }
        }

        // 移除协议类型
        public static bool UnregisterProtocol(string protocolType)
        {
            return _protocolMappings.Remove(protocolType);
        }

        // 获取所有支持的协议类型
        public static IEnumerable<string> GetSupportedProtocols()
        {
            return _protocolMappings.Keys;
        }

        public static IPLCService CreatePLCService(DeviceMapping device)
        {
            if (device == null)
                throw new ArgumentNullException(nameof(device));

            if (string.IsNullOrWhiteSpace(device.ProtocolType))
                throw new ArgumentException("协议类型不能为空");

            // 查找对应的协议创建器
            if (_protocolMappings.TryGetValue(device.ProtocolType.Trim(), out var creator))
            {
                return creator(device.Ip, device.Port);
            }

            throw new NotSupportedException($"不支持的协议类型: {device.ProtocolType}");
        }
    }
}
